{% extends "base.html" %}
{% block title %}Pilot{% endblock %}
{% block scripts %}
<script>
  $(document).ready(function() {
    $('#nav-pilot').addClass('active');

    var submitAjax = function(ev) {
      ev.preventDefault();
      var input = $(this);
      console.log(input);
      input.attr('disabled', 'disabled');
      var form = $(this).parents('.change-form');
      var formGroup = $(this).parents('.form-group');
      formGroup.removeClass('has-error');
      formGroup.removeClass('has-success');
      var data = form.serializeArray();
      input.val(input.checked);
      if (input.attr('type') == 'checkbox') {
        input.val(input.prop('checked'));
      }
      console.log(input.val());
      data.push({name: input.attr('name'), value: input.val()});
      $.ajax({
          type: form.attr('method'),
          url: form.attr('action'),
          data: data,
          error: function(xhr, msg, err) {
            console.log(err);
            formGroup.addClass('has-error');
            input.removeAttr('disabled');
          },
          success: function() {
            formGroup.addClass('has-success');
            setTimeout(function() {
              formGroup.removeClass('has-success');
            }, 30000);
            input.removeAttr('disabled');
          }
      });
    }

    $('.instructor-input').change(LookupInstructor);
    $('.change-form .blur').blur(submitAjax);
    $('.change-form .change').change(submitAjax);
    $('.simple-ajax-form').submit(function(ev) {
      ev.preventDefault();
      var form = $(this);
      var data = form.serializeArray();
      $.post(form.attr('action'), data, function(json) {
        console.log(json);
        var submit = form.find('button[type=submit]');
        submit.addClass('has-success');
        setTimeout(function() {
          submit.removeClass('has-success');
        }, 30000);
        newEndorsement(json.date, json.instructor.name, json.details);
      }, 'json');
    });

    $('#photo-upload-link').click(function(ev) {
      ev.preventDefault();
      $('#photo-upload').click();
    });

    var bfrSigPad = $('#bfr-form').signaturePad({
        drawOnly: true,
        lineTop: 140,
        output: '#bfr-signature',
        validateFields: false,
    });

    $('.simple-ajax-form.sigPad').signaturePad({
        drawOnly: true,
        lineTop: 140,
        validateFields: false,
    });

    {% if bfr_instructor is defined %}
    var jsonString = '{{ bfr_instructor.signature }}';
    if (jsonString != 'None') {
      bfrSigPad.regenerate($.parseJSON(jsonString));
    }
    {% endif %}

    $('#sig-save').click(function() {
      $('#bfr-signature').change();
    });

    $('#photo-upload').change(function() {
      $('#photo-form').submit();
    });

    var newEndorsement = function(dateString, name, details, key) {
      var endorsement = $('<div class="endorsement row well" />');
      var topRow = $('<div class="row" />');
      topRow.appendTo(endorsement);
      $('<div class="col-2" />').html(dateString).appendTo(topRow);
      $('<div class="col-2 col-offset-7" />').html(name).appendTo(topRow);
      var buttonContainer = $('<div class="col-1 pull-right" />');
      buttonContainer.appendTo(topRow);
      var button = $('<button class="delete glyphicon glyphicon-trash" />');
      if (key != undefined) {
        button.attr('id', key);
      }
      button.appendTo(buttonContainer);
      var bottomRow = $('<div class="row" />');
      bottomRow.appendTo(endorsement);
      $('<p />').html(details).appendTo(bottomRow);
      $('#endorsements').append(endorsement);
    }

    {% for e in endorsements %}
      newEndorsement('{{ e.date }}', '{{ e.instructor.id() }}', '{{ e.details }}', '{{ e.key.urlsafe() }}');
    {% endfor %}
    $('.delete').click(function() {
      var button = $(this);
      var endorsement = button.attr('id');
      $('#delete-endorsement').val(endorsement);
      $('#confirm').modal('show');
    });
    $('#delete-endorsement').click(function(ev) {
      var data = new Array();
      var endorsement = $(this).val();
      data.push({name: "delete", value: true});
      data.push({name: "endorsement", value: endorsement});
      $.post('/endorsement', data, function() {
        $('#' + endorsement).parents('.endorsement').remove();
        $('#confirm').modal('hide');
      })
    });
    $('#ifr-currency').popover();
  });
</script>
{% endblock scripts %}

{% block body %}
<div id="confirm" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <h4 class="modal-title">Are you sure?</h4>
      </div>
      <div class="modal-footer">
        <button type="button" data-dismiss="modal" class="btn btn-default">Cancel</button>
        <button id="delete-endorsement" type="button" class="btn btn-danger">Delete</button>
      </div>
    </div>
  </div>
</div>
<div class="container">
  <div class="row">
    <div class="col-sm-7 col-lg-6 well well-small">
      <div class="thumbnail">
        <form method="POST" action="{{ upload_url }}" enctype="multipart/form-data" id="photo-form">
          <input type="hidden" name="pilot" value="{{ pilot.key.urlsafe() }}">
          <input type="file" class="hide" name="upload" id="photo-upload">
        </form>
        <a href="#" id="photo-upload-link">
        {% if pilot.photo_url %}
          <img class="img-responsive" src="{{ pilot.photo_url }}" alt="" id="photo">
        {% else %}
          <img class="img-responsive" data-src="holder.js/400x286" alt="" id="photo">
        {% endif %}
        </a>
        <div class="caption">
          <form class="form-horizontal change-form" method="POST" action="/pilot">
            <div class="form-group">
              <label for="pilot-name" class="col-sm-5 control-label">Name</label>
              <div class="col-sm-7">
                <input type="text" class="form-control change" name="name" placeholder="Name" id="pilot-name" value="{{ pilot.name if pilot.name }}">
              </div>
            </div>
            <div class="form-group">
              <label for="pilot-birthday" class="col-sm-5 control-label">Birthday</label>
              <div class="col-sm-7">
                <input type="date" class="form-control blur" name="birthday" id="pilot-birthday" value="{{ pilot.birthday if pilot.birthday }}">
              </div>
            </div>
            <div class="form-group">
              <label for="pilot-cert-type" class="col-sm-5 control-label">Certificate Type</label>
              <div class="col-sm-7">
                <input type="text" class="form-control change" name="cert_type" placeholder="Certificate Type" id="pilot-cert-type" value="{{ pilot.cert_type if pilot.cert_type }}">
              </div>
            </div>
            <div class="form-group">
              <label for="pilot-cert-num" class="col-sm-5 control-label">Certificate Number</label>
              <div class="col-sm-7">
                <input type="text" class="form-control change" name="cert_num" placeholder="Certificate Number" id="pilot-cert-num" value="{{ pilot.cert_num if pilot.cert_num }}">
              </div>
            </div>
            <div class="form-group">
              <label for="pilot-medical" class="col-sm-5 control-label">Last Medical</label>
              <div class="col-sm-7">
                <input type="date" class="form-control blur" name="last_medical" id="pilot-medical" value="{{ pilot.last_medical if pilot.last_medical }}">
              </div>
            </div>
            <div class="form-group">
              <label for="pilot-medical-type" class="col-sm-5 control-label">Medical Class</label>
              <div class="col-sm-7">
                <input type="number" class="form-control change" name="medical_type" placeholder="Medical Class" id="pilot-medical-type" value="{{ pilot.medical_type if pilot.medical_type }}">
              </div>
            </div>
            <div class="form-group">
              <label for="pilot-ifr" class="col-sm-5 control-label">Instrument rated?</label>
              <div class="col-sm-7">
                <input type="checkbox"
                 class="form-control change"
                 name="instrument"
                 id="pilot-ifr"
                 {{ "checked=checked" if pilot.instrument }}>
              </div>
            </div>
          </form>
        </div><!-- .caption -->
      </div><!-- .thumbnail -->
    </div><!-- pilot column -->
    <div class="col-sm-7 col-lg-6 well well-small">
      <legend>Currency</legend>
      <table class="table">
        <tr>
          <td>Medical expires</td>
          {% if medical_due is defined and medical_due[0] %}
          <td class="{{ medical_due[0] }}">{{ medical_due[1] }}</td>
          {% else %}
          <td>Unknown</td>
          {% endif %}
        </tr>
        <tr>
          <td>Flight review expires</td>
          {% if bfr_due is defined and bfr_due[0] %}
          <td class="{{ bfr_due[0] }}">{{ bfr_due[1] }}</td>
          {% else %}
          <td>Unknown</td>
          {% endif %}
        </tr>
        <tr>
          <td>Tailwheel currency expires</td>
          {% if tailwheel_due is defined and tailwheel_due[0] %}
          <td class="{{ tailwheel_due[0] }}">{{ tailwheel_due[1] }}</td>
          {% else %}
          <td>Unknown</td>
          {% endif %}
        </tr>
        <tr>
          <td>Cessna currency expires</td>
          {% if cessna_due is defined and cessna_due[0] %}
          <td class="{{ cessna_due[0] }}">{{ cessna_due[1] }}</td>
          {% else %}
          <td>Unknown</td>
          {% endif %}
        </tr>
        <tr>
          <td>Night currency expires</td>
          {% if night_due is defined and night_due[0] %}
          <td class="{{ night_due[0] }}">{{ night_due[1] }}</td>
          {% else %}
          <td>Unknown</td>
          {% endif %}
        </tr>
        <tr>
          <td>Instrument currency expires</td>
          {% if ifr_due is defined and ifr_due[0] %}
          <td class="{{ ifr_due[0] }}"
           id="ifr-currency"
           data-toggle="popover"
           data-placement="top"
           data-html="true"
           data-original-title="Recent approaches"
           data-content="
              <ul>
              {% for approach in recent_approaches %}
                <li>{{ approach.strftime('%Y-%m-%d') }}</li>
              {% endfor %}
              </ul>"
          >{{ ifr_due[1] }}</td>
          {% else %}
          <td>Unknown</td>
          {% endif %}
        </tr>
      </table>
    </div><!-- currency column -->
    {% if stats is defined %}
    <div class="col-sm-7 col-lg-6 well well-small">
      <legend>Flight Hours</legend>
      <table class="table table-hover">
        <thead>
          <tr><td>Type</td><td>Number of hours</td></tr>
        </thead>
        <tbody>
          <tr>
            <td>PIC hours</td><td>{{ stats.pic_hours }}</td>
          </tr>
          <tr>
            <td>Tailwheel hours</td><td>{{ stats.tailwheel_hours }}</td>
          </tr>
          <tr>
            <td>Cross country hours</td><td>{{ stats.xc_hours }}</td>
          </tr>
          <tr>
            <td>Night hours</td><td>{{ stats.night_hours }}</td>
          </tr>
          <tr>
            <td>IMC hours</td><td>{{ stats.imc_hours }}</td>
          </tr>
          <tr>
            <td>Simulated IMC hours</td><td>{{ stats.sim_imc_hours }}</td>
          </tr>
          <tr>
            <td>Simulator hours</td><td>{{ stats.simulator_hours }}</td>
          </tr>
          <tr>
            <td>Dual instruction hours</td><td>{{ stats.dual_hours }}</td>
          </tr>
          <tr>
            <td>Ground instruction hours</td><td>{{ stats.ground_instruction_hours }}</td>
          </tr>
          <tr>
            <td>Instrument rating training hours</td><td>{{ stats.instrument_rating_training_hours }}</td>
          </tr>
          {% for a in stats.aircraft_stats %}
          <tr>
            <td>{{ a.make_model }}</td><td>{{ a.hours }}</td>
          </tr>
          {% endfor %}
          <tr>
            <td>Total time</td><td>{{ stats.total_hours }}</td>
          </tr>
        </tbody>
      </table>
      <legend>Statistics</legend>
      <table class="table table-hover">
        <tbody>
          <tr>
            <td>Number of flights</td><td>{{ stats.total_num_flights }}</td>
          </tr>
          <tr>
            <td>Number of landings</td><td>{{ stats.num_landings }}</td>
          </tr>
          <tr>
            <td>Number of instrument approaches</td><td>{{ stats.num_approaches }}</td>
          </tr>
          <tr>
            <td>Total cost</td><td>{{ "${:,.2f}".format(stats.total_cost) }}</td>
          </tr>
        </tbody>
      </table>
    </div><!-- stats column -->
    {% endif %}
  </div><!-- top row -->
  <div class="row"><!-- second row -->
    <div class="col-sm-7 col-lg-6 well well-small">
      <legend>Biennial Flight Review</legend>
      <form id="bfr-form" method="POST" class="change-form sigPad" action="/endorsement">
        <input type="hidden" name="bfr" value="1">
        <input type="hidden" name="endorsement" value="{{ bfr.key.urlsafe() if bfr }}">
        <div class="form-group">
          <label>Date</label>
          <input type="date" class="form-control blur" name="date" value="{{ bfr.date if bfr }}">
        </div>
        <div class="form-group">
          <label>Details</label>
          <textarea rows=3 class="form-control change" name="details">{{ bfr.details if bfr }}</textarea>
        </div>
        <div class="form-group">
          <label>Instructor Name</label>
          <input type="text" class="form-control instructor-input" name="name" placeholder="Name" value="{{ bfr_instructor.name if bfr_instructor }}">
        </div>
        <div class="form-group">
          <label>Certificate number</label>
          <input type="text" class="form-control change" name="cert" placeholder="Certificate number" value="{{ bfr_instructor.cert if bfr_instructor and bfr_instructor.cert }}">
        </div>
        <div class="form-group">
          <label>Certificate expiration</label>
          <input type="date" class="form-control blur" name="expiration" placeholder="Expiration" value="{{ bfr_instructor.expiration if bfr_instructor and bfr_instructor.expiration }}">
        </div>
        <div class="form-group">
          <label>Signature</label>
          <div class="sig sigWrapper">
            <input type="hidden" name="signature" class="change" id="bfr-signature">
            <canvas class="pad" width="398" height="148"></canvas>
          </div>
        </div>
        <div class="form-group">
          <button type="button" class="btn clearButton">Clear signature</button>
          <button type="button" id="sig-save" class="btn btn-primary">Save</button>
        </div>
      </form>
    </div><!-- BFR column -->
  </div><!-- second row -->
  <div class="row">
    <h3>Endorsements</h3>
    <hr />
    <div id="endorsements" class="col-12">
    </div>
    <div class="col-6 well well-small">
      <form method="POST" class="simple-ajax-form sigPad" action="/endorsement">
        <legend>New endorsement</legend>
          <div class="form-group">
            <label>Date</label>
            <input type="date" class="form-control" name="date">
          </div>
          <div class="form-group">
            <label>Details</label>
            <textarea rows=3 class="form-control" name="details"></textarea>
          </div>
          <div class="form-group">
            <label>Instructor Name</label>
            <input type="text" class="form-control instructor-input" name="name" placeholder="Name">
          </div>
          <div class="form-group">
            <label>Certificate number</label>
            <input type="text" class="form-control" name="cert" placeholder="Certificate number">
          </div>
          <div class="form-group">
            <label>Certificate expiration</label>
            <input type="date" class="form-control" name="expiration" placeholder="Expiration">
          </div>
          <div class="form-group">
            <label>Signature</label>
            <div class="sig sigWrapper">
              <input type="hidden" class="output" name="signature">
              <canvas class="pad" width="398" height="148"></canvas>
            </div>
          </div>
          <div class="form-group">
            <button type="button" class="btn clearButton">Clear signature</button>
            <button type="submit" class="btn btn-primary">Add</button>
          </div>
      </form>
    </div>
  </div><!-- third row -->
</div><!-- Top level .container -->
{% endblock body %}
